package com.lenovo;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

/**
 * @author Howie Lu
 * @version Updated at 2019/05/24
 * @description 配置多源数据库，每个数据源都要有一个配置类
 */
@Configuration
//扫描dao层接口，以及对应的SqlSessionFactory
@MapperScan(basePackages = "com.lenovo.codestatreport.**.mapper", sqlSessionFactoryRef = "githubSqlSessionFactory")
public class GitCodeStatDataSourceConfig {
    @Bean(name = "githubDataSource")
    //约定properties中该数据源的前缀
    @ConfigurationProperties("spring.datasource.gitcodestat")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "githubSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("githubDataSource") DataSource githubData) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(githubData);
        //设置dao实现层的位置
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/gitCodeStatDatabase/*Mapper.xml"));
        return sessionFactoryBean.getObject();
    }
}
